package com.bing.sina;

import com.bing.beans.Person;
import com.bing.beans.Search;
import com.bing.beans.WeiBo;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by kaibb on 14-8-3.
 */

@Service
@Transactional
public class SinaJdbc {

    private static final Logger logger = LoggerFactory.getLogger(SinaJdbc.class);
    @Autowired
    @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;

    public Person findPerson(String url) {
        Query query = sessionFactory.getCurrentSession().createQuery(" from Person where url = :url");
        query.setParameter("url", url);
        return (Person) query.uniqueResult();
    }

    public void resetPerson(Person person) {
        logger.info("重置人物:{}", person);
        Session session = sessionFactory.getCurrentSession();
        person.getGuanZhuPerson().clear();
        for (WeiBo weiBo : person.getWeiBo()) {
            weiBo.setPerson(null);
            session.delete(weiBo);
        }
        person.getFenSiPerson().clear();
        session.update(person);
    }

    public void savePerson(Person person) {
        sessionFactory.getCurrentSession().saveOrUpdate(person);
    }

    public void saveWeiBo(WeiBo weiBo) {
        sessionFactory.getCurrentSession().saveOrUpdate(weiBo);
    }

    public void saveFenSi(Person person, Person p) {
        logger.info("保存粉丝:{} , {}", person.getId(), p.getId());
        Query query = sessionFactory.getCurrentSession().createSQLQuery("insert into fensi (person_id,fensi_id) values(:person_id,:fensi_id)");
        query.setParameter("person_id", person.getId());
        query.setParameter("fensi_id", p.getId());
        query.executeUpdate();
    }

    public void saveGuanZhu(Person person, Person p) {
        logger.info("保存关注:{} , {}", person.getId(), p.getId());
        Query query = sessionFactory.getCurrentSession().createSQLQuery("insert into GuanZhu (person_id,guanzhu_id) values(:person_id,:guanzhu_id)");
        query.setParameter("person_id", person.getId());
        query.setParameter("guanzhu_id", p.getId());
        query.executeUpdate();
    }

    public void saveSearch(Search search) {
        sessionFactory.getCurrentSession().saveOrUpdate(search);
    }
}
